<template>
  <row class="view-chat">
    <left v-loading="loading" v-empty="emptyUsers">
        <search class="search-box"></search>
        <chat-list :data="chatList" @select="handleSelect" />
    </left>
    <center>
      <router-view v-slot="{ Component }">
        <transition appear name="slide">
          <component :is="Component" :data="SelectChat"/>
        </transition>
      </router-view>
    </center>
  </row>
</template>
<script>
import { defineComponent } from 'vue'
import Search from '@/components/wrapSearch'
import ChatList from '@/components/chatList/chatList.vue'
import storage from 'good-storage'
import { CURRENT_CHAT_KEY } from '@/assets/js/constant'
import { getChatList } from '@/service'
export default defineComponent({
  name: 'Chat',
  components: {
    Search,
    ChatList
  },
  computed: {
    loading() {
      return !this.chatList.length
    },
    emptyUsers() {
      return !this.chatList.length
    }
  },
  data() {
    return {
      chatList: [],
      SelectChat: null
    }
  },
  async created() {
    const chatList = await getChatList()
    this.chatList = chatList
    if (!this.SelectChat) {
      const cached = storage.session.get(CURRENT_CHAT_KEY)
      if (cached) {
        this.handleSelect(cached)
      }
    }
  },
  methods: {
    handleSelect(chat) {
      this.SelectChat = chat
      this.cacheChat(chat)
      this.$router.push({
        path: `/chat/${chat.groupId}`
      })
    },
    cacheChat(chat) {
      storage.session.set(CURRENT_CHAT_KEY, chat)
    }
  }
})
</script>

<style lang="scss" scoped>
  .layout-center {
    background-color: $color-text-d;
  }
  .layout-left,
  .layout-left-scroll {
    height: 100%;
    overflow: hidden;
  }
  .search-box {
    margin: 16px 8px;
  }
</style>
